<template>
	<view class="good_details">
		<!-- <u-swiper :list="list1" @change="handleChange" indicator :radius="0" height="420rpx" :current="current"
			:autoplay="false"></u-swiper> -->
		<view class="good_details_swiper">
			<swiper class="swiper-img" :current="current" :duration="300" @change="handleChange" circular
				:autoplay="autoplay">
				<swiper-item class="swiper-item" v-for="(item, index) in list1" :key="index">
					<view class="img-page">
						<movable-area scale-area v-if="item?.type === 'image'">
							<movable-view direction="all" scale="true" scale-min="1" scale-max="4">
								<image class="max-img" :src="item.url" :lazy-load="true" mode="aspectFill" />
							</movable-view>
						</movable-area>
						<!--  muted show-mute-btn -->
						<video class="max-img" :src="item.url" :lazy-load="true" mode="aspectFit" v-else
							:id="'goodDetailsVideo'+index" controls @ended="handleEndex" />
					</view>
				</swiper-item>
			</swiper>
			<view class="swiper_indicator">
				<text v-for="(item, index) in list1" :key="'indicator'+index"
					:class="{'indicator__dot--active':index === current}"></text>
			</view>
		</view>
		<view class="good_details_price">
			<view class="good_details_price_left">
				<view class="good_details_price_1">
					<text
						v-if="goodsInfo?.qxGoodsManage?.discountPrice">￥</text>{{goodsInfo?.qxGoodsManage?.discountPrice}}
				</view>
				<text class="good_details_price_2">到手价&nbsp;&nbsp;￥{{goodsInfo?.qxGoodsManage?.originalPrice}}</text>
			</view>
			<view class="good_details_price_right" @click="handleCollect">
				<image src="http://qianxueapplet.suoeryun.com/collectSelected.png"
					v-if="goodsInfo?.qxGoodsManage?.isCollect">
				</image>
				<image src="http://qianxueapplet.suoeryun.com/collect.png" v-else>
				</image>
			</view>
		</view>
		<view class="good_details_title">
			<view class="good_details_title_1">{{goodsInfo?.qxGoodsManage?.goodsName}}</view>
			<text class="good_details_title_2">销量: <template>{{goodsInfo?.qxGoodsManage?.salesVolume}}</template>
				<!-- salesReality 实际销量-->
				<!-- <template v-else>{{goodsInfo?.qxGoodsManage?.salesVolume}}</template> -->
			</text>
		</view>
		<view class="good_details_address">
			<view class="good_details_address_item" @click="handleOpenType">
				<view class="good_details_address_item_1">已选</view>
				<view class="good_details_address_item_2 overflow">
					<template v-if="selectedAttr">
						{{selectedAttr?.specifications}} x {{orderNum}}</template>
					<template v-else>*{{orderNum}}</template>
				</view>
				<image class="good_details_address_item_3 " src="http://qianxueapplet.suoeryun.com/moreDot.png">
				</image>
			</view>
			<view class="good_details_address_item" @click="handleChangeAddress" v-if="defaultAddress">
				<view class="good_details_address_item_1">送至</view>
				<view class="good_details_address_item_2 overflow">
					<template v-if="defaultAddress">
						{{defaultAddress?.consignee}}
						{{maskPhoneNumber(defaultAddress?.phoneNumber)}}
						<template v-if="defaultAddress?.location">
							{{defaultAddress?.location?.replaceAll(',','')}}</template>
						{{defaultAddress?.address}}
					</template>
					<template v-else>请选择收货地址</template>
				</view>
				<image class="good_details_address_item_3" src="http://qianxueapplet.suoeryun.com/moreDot.png"></image>
			</view>
		</view>
		<view class="good_details_evaluation" @click.stop="handleAllEvaluation">
			<view class="good_details_card_title">
				<view class="good_details_card_title_left">
					<image src="http://qianxueapplet.suoeryun.com/shuxian.png"></image>
					<text>商品评价（{{goodsInfo?.qxGoodsEvaluateNum}}）</text>
				</view>
				<view class="good_details_card_title_right">
					<text>{{goodsInfo?.highRate}}好评</text>
					<u-icon name="arrow-right" color="#979797" size="10"></u-icon>
				</view>
			</view>
			<template v-if="goodsInfo?.qxGoodsEvaluateList && goodsInfo?.qxGoodsEvaluateList?.length > 0">
				<view class="good_details_evaluation_item" v-for="item in goodsInfo?.qxGoodsEvaluateList"
					:key="item?.id">
					<view class="good_details_evaluation_item_header">
						<view class="good_details_evaluation_item_header_left">
							<image :src="item?.avatar" class="good_details_evaluation_item_header_left_avatar"></image>
							<view class="good_details_evaluation_item_header_left_nick">
								<text
									class="good_details_evaluation_item_header_left_nick_1">{{item?.evaluateUserNickname}}</text>
								<text class="good_details_evaluation_item_header_left_nick_2">{{item?.fromToday}}</text>
							</view>
						</view>
						<u-rate :count="5" active-color="#FF943C" readonly v-model="item.evaluateScore"></u-rate>
					</view>
					<view class="good_details_evaluation_item_content">{{item?.evaluateContent}}</view>
				</view>
			</template>
			<u-empty v-else marginTop="20" text="暂无评论～" icon="http://qianxueapplet.suoeryun.com/zupj.png"></u-empty>
		</view>
		<view class="good_details_info">
			<view class="good_details_card_title" style="margin-bottom: 20rpx;">
				<view class="good_details_card_title_left">
					<image src="http://qianxueapplet.suoeryun.com/shuxian.png"></image>
					<text>商品信息</text>
				</view>
			</view>
			<rich-text class="good_details_info_content"
				:nodes="handleFormat(goodsInfo?.qxGoodsManage?.goodsDetails)"></rich-text>
			<view class="good_details_info_btn safe_area"></view>
		</view>
		<view class="good_details_btm safe_area">
			<view class="good_details_btm_btn">
				<view class="good_details_btm_btn_fun" @click="handleHome">
					<image src="http://qianxueapplet.suoeryun.com/jumpHomepage.png"></image>
					<text>首页</text>
				</view>
				<button class="good_details_btm_btn_fun" open-type="contact">
					<image src="http://qianxueapplet.suoeryun.com/service.png"></image>
					<text>客服</text>
				</button>
				<!-- <view class="good_details_btm_btn_fun" @click="handleCollect">
					<image src="http://qianxueapplet.suoeryun.com/collectSelected.png"
						v-if="goodsInfo?.qxGoodsManage?.isCollect">
					</image>
					<image src="http://qianxueapplet.suoeryun.com/collect.png" v-else>
					</image>
					<text>收藏</text>
				</view> -->
				<button class="good_details_btm_btn_btn" @click="handleOpenType"
					:disabled="!defaultAddress?.templateId && defaultAddress">立即购买</button>
			</view>
		</view>
	</view>
	<!-- 商品规格 -->
	<goodsType ref="goodsTypeRef"></goodsType>
	<!-- 配送地址 -->
	<distributionAddress ref="distributionAddressRef"></distributionAddress>
</template>

<script lang="ts" setup>
	import { onMounted, onUnmounted, ref, getCurrentInstance, unref } from 'vue';
	import goodsType from '@/components/goodsType';
	import distributionAddress from '@/components/distributionAddress';
	import { qxGoodsManageQueryById, getWxUserDefaultAddress, queryFreightByGoodsIdALocationCode } from '@/config/goodStuff.api';
	import { qxCommentCollectEdit } from '@/config/index.api';
	import { onLoad } from "@dcloudio/uni-app";
	import { maskPhoneNumber, handleFormat } from '@/util/index';

	const goodsTypeRef = ref();
	const distributionAddressRef = ref();
	const goodsInfo = ref();
	const defaultAddress = ref();
	const { proxy } = getCurrentInstance();
	const selectedAttr = ref();
	const orderNum = ref(1);

	const list1 = ref([]);
	const loadParams = ref();
	const current = ref(0);
	const videoCtx = ref();
	const autoplay = ref(false);

	onLoad(async (params) => {
		loadParams.value = params;
		loadPageData();
	})

	onMounted(() => {
		// 刷新页面
		uni.$on('refreshPage', item => {
			loadPageData();
		})

		// 更新地址
		uni.$on('changeAddress', async (item) => {
			console.log(item, 'changeAddress-监听');
			defaultAddress.value = item;
			// 查询运费
			// queryFreight(item);
		})
	})

	onUnmounted(() => {
		// 销毁监听-更新地址
		uni.$off('refreshPage');
		// 销毁监听-更新地址
		uni.$off('changeAddress');
	})

	/**
	 * 查询运费
	 */
	async function queryFreight(item) {
		const res = await queryFreightByGoodsIdALocationCode({ freightTemplateId: unref(goodsInfo)?.qxGoodsManage?.freightTemplateId, locationCode: item?.locationCode?.split(',')[0] });
		defaultAddress.value.templateId = res?.id;//邮费Id
		defaultAddress.value.templateName = res?.templateName;//邮费名称
		defaultAddress.value.freightCharges = res?.freightCharges;//运费金额
	}

	/**
	 * 加载界面数据
	 */
	async function loadPageData() {
		const params = unref(loadParams);
		// 根据id
		if (params?.id) {
			const res = await qxGoodsManageQueryById({ id: params?.id, userId: unref(proxy['vuex_user'])?.id });
			goodsInfo.value = res;
			for (let i = 0; i < res?.qxGoodsAttributeManageList?.length; i++) {
				if (res?.qxGoodsAttributeManageList[i]?.inventory !== 0) {
					selectedAttr.value = res?.qxGoodsAttributeManageList[i];
					break;
				}
			}
			list1.value = res?.qxGoodsPictureList;
			// 商品下架
			if (res?.qxGoodsManage?.shelvesState === '2') {
				uni.showModal({
					content: '商品已下架',
					confirmColor: '#FF943C',
					showCancel: false,
					confirmText: '我已知晓',
					success: function (res) {
						uni.$emit('goodStuffLoadData');
						uni.navigateBack();
					}
				})
				return;
			}
			videoPlayPause();
		}
		// 默认收货地址
		const result = await getWxUserDefaultAddress({});
		if (!uni.$u.test.isEmpty(result)) {
			defaultAddress.value = result;
			// 查询运费
			queryFreight(result);
		}
	}

	/**
	 * 视频播放暂停
	 */
	function videoPlayPause() {
		if (unref(videoCtx)) {
			videoCtx.value.pause();
		}
		if (unref(list1)?.length > 0 && unref(list1)[unref(current)].type === 'video') {
			videoCtx.value = uni.createVideoContext(`goodDetailsVideo${unref(current)}`);
			autoplay.value = false;
			setTimeout(_ => {
				videoCtx.value.play();
			}, 200)
		} else {
			autoplay.value = true;
		}
	}

	/**
	 * 当播放到末尾时触发 ended 事件
	 */
	function handleEndex() {
		if (unref(current) === unref(list1)?.length - 1) {
			current.value = 0;
		} else {
			current.value += 1;
		}
	}

	/**
	 * 轮播图监听
	 */
	function handleChange(e) {
		current.value = e.target.current;
		videoPlayPause();
	}

	/**
	 * 打开商品类型
	 */
	function handleOpenType() {
		const address = unref(defaultAddress);//地址
		const goods = unref(goodsInfo);//商品信息
		// if (uni.$u.test.isEmpty(address)) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '请选择收货地址',
		// 	})
		// 	return
		// }
		// // 收货地址是否配送
		// if (uni.$u.test.isEmpty(unref(freight))) {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '该地址不支持配送',
		// 	})
		// 	return
		// }
		goodsTypeRef.value.handleShow({
			list: goodsInfo.value?.qxGoodsAttributeTreeNodeList,//商品属性列表
			combinationList: goodsInfo.value?.qxGoodsAttributeManageList,//商品属性组合列表
			selectedAttr: unref(selectedAttr) ?? { price: goodsInfo.value?.qxGoodsManage?.originalPrice, inventory: goodsInfo.value?.qxGoodsManage?.storage },//选择属性
			orderNum: unref(orderNum),//选择数量
			orderInfo: {
				location: address?.location,//收货地区
				locationCode: address?.locationCode,//收货地区code
				address: address?.address,//收货详情地址
				phoneNumber: address?.phoneNumber,//收货人手机号码
				consignee: address?.consignee,//收货人名称
				goodsId: goods?.qxGoodsManage?.id,//商品ID
				goodsName: goods?.qxGoodsManage?.goodsName,//商品名称
				goodsImages: goods?.qxGoodsManage?.goodsCover,//商品图片
				afterSalesDate: goods?.qxGoodsManage?.afterSalesDate,//售后日期
				freightTemplateId: goods?.qxGoodsManage?.freightTemplateId,//模板id
				categoryId: goods?.qxGoodsManage?.goodsCategoryId,//商品类别id
				categoryName: goods?.qxGoodsManage?.goodsCategoryName,//商品类别名称
				templateId: address?.templateId || goods?.qxGoodsManage?.freightTemplateId,//邮费Id
				templateName: address?.templateName,//邮费名称
				freightCharges: address?.freightCharges,//运费金额
			}
		})
	}

	/**
	 * 全部评价
	 */
	function handleAllEvaluation() {
		uni.$u.route('/pages/goodStuff/allEvaluation', {
			id: goodsInfo.value?.qxGoodsManage?.id
		});
	}

	/**
	 * 弹出层打开-修改地址
	 */
	function handleChangeAddress() {
		distributionAddressRef.value.handleShow({ ...unref(defaultAddress), freightTemplateId: unref(goodsInfo)?.qxGoodsManage?.freightTemplateId });
	}

	/**
	 * 首页
	 */
	function handleHome() {
		uni.$u.route({
			url: 'pages/index/index',
			type: 'switchTab'
		})
	}

	/**
	 * 收藏
	 */
	function handleCollect() {
		uni.$u.throttle(async function () {
			await qxCommentCollectEdit({
				collectType: '2',
				collectId: goodsInfo.value?.qxGoodsManage?.id,
				isCollect: goodsInfo.value?.qxGoodsManage?.isCollect,
				collectName: goodsInfo.value?.qxGoodsManage?.goodsName,
				collectPrice: goodsInfo.value?.qxGoodsManage?.originalPrice,
				collectCover: goodsInfo.value?.qxGoodsManage?.goodsCover,
			});
			goodsInfo.value.qxGoodsManage.isCollect = !goodsInfo.value?.qxGoodsManage?.isCollect;
			uni.showToast({
				icon: 'none',
				title: goodsInfo.value.qxGoodsManage.isCollect ? '收藏成功' : '取消收藏'
			})
		}, 1000)
	}
</script>

<style lang="scss" scoped>
	.good_details {
		.good_details_swiper {
			position: relative;

			.swiper-img {
				height: 420rpx;
				// background-color: #000000;


				movable-view {
					display: flex;
					align-items: center;
					justify-content: center;

					width: 100vw;
					height: 420rpx;
				}

				movable-area {
					position: fixed;
					overflow: hidden;
					width: 100vw;
					height: 420rpx;

					transform: scale();
				}

				image,
				video {
					width: 100%;
					height: 420rpx;
				}
			}

			.swiper_indicator {
				position: absolute;
				bottom: 20rpx;
				display: flex;
				flex-direction: row;
				justify-content: center;
				width: 100vw;

				text {
					display: inline-block;
					height: 12rpx;
					width: 12rpx;
					border-radius: 50%;
					background-color: hsla(0, 0%, 100%, .35);
					margin: 0 5px;
					// transition: background-color .3s;

					&.indicator__dot--active {
						background-color: #fff;
					}
				}
			}

			// @keyframes background-color {
			// 	transition-behavior: normal;
			// 	transition-duration: 0.3s;
			// 	transition-timing-function: ease;
			// 	transition-delay: 0s;
			// 	transition-property: background-color;
			// }
		}

		.good_details_price {
			padding-bottom: 18rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #FF3535;
			padding: 20rpx 24rpx 0 24rpx;
			background-color: #FFF;

			.good_details_price_left {
				display: flex;
				align-items: flex-end;

				.good_details_price_1 {
					font-size: 60rpx;
					line-height: 56rpx;
					display: flex;
					align-items: flex-end;
					padding-right: 12rpx;

					text {
						font-size: 32rpx;
						line-height: 45rpx;
					}
				}

				.good_details_price_2 {
					background-color: #FF3535;
					border-radius: 8rpx;
					opacity: 1;
					font-size: 24rpx;
					color: #fff;
					display: inline-block;
					padding: 8rpx 10rpx;
					// text-decoration: line-through;
				}
			}

			.good_details_price_right {
				image {
					width: 48rpx;
					height: 48rpx;
				}
			}
		}

		.good_details_title {
			padding: 30rpx 30rpx 20rpx 30rpx;
			background-color: #fff;

			.good_details_title_1 {
				font-size: 36rpx;
				font-weight: 500;
			}

			.good_details_title_2 {
				display: inline-block;
				padding: 4rpx 10rpx;
				color: #FF3535;
				background-color: #FFEAEA;
				font-size: 28rpx;
				margin-top: 10rpx;
			}
		}

		.good_details_address {
			padding: 0 24rpx 24rpx 24rpx;
			background-color: #fff;
			margin: 20rpx 0;

			.good_details_address_item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1px solid #F7F7F7;
				padding: 32rpx 0;

				.good_details_address_item_1 {
					display: inline-block;
					font-size: 32rpx;
					font-weight: 700;
					padding-right: 28rpx;
				}

				.good_details_address_item_2 {
					width: calc(100vw - 24rpx - 48rpx - 128rpx);
					font-size: 30rpx;
					text-align: left;
				}

				.good_details_address_item_3 {
					width: 48rpx;
					height: 48rpx;
				}
			}
		}

		.good_details_card_title {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.good_details_card_title_left {
				display: flex;
				align-items: center;
				font-size: 36rpx;
				font-weight: 500;

				image {
					width: 6rpx;
					height: 28rpx;
					margin-right: 12rpx;
				}
			}

			.good_details_card_title_right {
				display: flex;
				align-items: center;
				color: #A1A7AD;
				font-size: 28rpx;

				text {
					margin-right: 10rpx;
				}
			}

		}

		.good_details_evaluation {
			background-color: #fff;
			padding: 26rpx 24rpx;
			margin-bottom: 20rpx;

			.good_details_evaluation_item {
				padding-top: 24rpx;

				.good_details_evaluation_item_header {
					display: flex;
					justify-content: space-between;
					align-items: flex-start;

					.good_details_evaluation_item_header_left {
						display: flex;

						&>image {
							width: 76rpx;
							height: 76rpx;
							margin-right: 16rpx;
							border-radius: 50%;
						}

						.good_details_evaluation_item_header_left_nick {
							display: flex;
							flex-direction: column;
							justify-content: space-between;

							.good_details_evaluation_item_header_left_nick_1 {
								font-size: 28rpx;
							}

							.good_details_evaluation_item_header_left_nick_2 {
								font-size: 24rpx;
								color: #9AAFBC;
							}
						}
					}
				}

				.good_details_evaluation_item_content {
					padding-top: 24rpx;
					font-size: 28rpx;
					line-height: 50rpx;
				}
			}
		}

		.good_details_info {
			background-color: #fff;
			padding: 24rpx;

			.good_details_info_content {
				// padding: 24rpx;
				display: block;

				img {
					width: 100% !important;
				}
			}

			.good_details_info_btn {
				height: 88rpx;
			}
		}

		.good_details_btm {
			background-color: #fff;
			position: fixed;
			bottom: 0;
			width: 100vw;
			box-shadow: 0 6rpx 16rpx 0 rgba(0, 0, 0, 0.24);

			.good_details_btm_btn {
				display: flex;
				justify-content: space-around;
				align-items: center;

				.good_details_btm_btn_fun {
					display: flex;
					align-items: center;
					flex-direction: column;
					padding: 10rpx 0;
					margin: 0;
					background-color: transparent;

					&::after {
						border: 0;
					}

					image {
						width: 44rpx;
						height: 44rpx;
						margin: 6rpx;
					}

					text {
						font-size: 10px;
						line-height: 10px;
					}
				}

				.good_details_btm_btn_btn {
					margin: 0;
					padding: 0;
					width: 460rpx;
					height: 70rpx;
					line-height: 68rpx;
					background-color: #FF943C;
					color: #fff;
					font-size: 30rpx;
					border-radius: 600rpx;
					font-weight: 500;

					&[disabled]:not([type]) {
						opacity: 0.5;
					}

					&::after {
						border: 0;
					}
				}
			}
		}
	}
</style>